from django.shortcuts import render, render_to_response

# Create your views here.
from Blog.models import *
from Blog.forms import CommentForm,UserForm
from django.http import Http404
from django import forms


def get_blogs(request):
    blogs = Blog.objects.all().order_by('-created')
    # 获得所有的博客按时间排序
    return render_to_response('blog-list.html', {'blogs': blogs})
    # 
def get_details(request, blog_id):
    try:
        blog = Blog.objects.get(id=blog_id)
        # get用于查询单条记录,blog_id urls.py传入
    except Blog.DoesNotExist:
        raise Http404
        # 如果未查询到,返回404
    if request.method == 'GET':
        form = CommentForm()
    else:#请求方法为post
        form = CommentForm(request.POST)# 将接收到的数据通过CommentForm验证
        if form.is_valid():
        # 验证请求的内容和CommentForm里面的是否验证通过。通过是True，否则False。
            cleaned_data = form.cleaned_data
            # cleaned_data 就是读取表单返回的值，返回类型为字典dict型
            cleaned_data['blog'] = blog
            # 由前面传入
            Comment.objects.create(**cleaned_data)
            # 
    ctx = {
        'blog': blog,
        'comments': blog.comment_set.all().order_by('-created'),
        #
        'form': form
    }
    # 使用render_to_response的话就无法对表单进行验证了，
    # 所以还是需要使用render方法。如果去掉模板中的{% csrf_token %} 用于防跨域请求。就可以了
    return render(request, 'blog_details.html', ctx)


def register(request):
    """
    还未解决
    """
    if request.method == "POST":
        uf = UserForm(request.POST)
        if uf.is_valid():
            #获取表单信息
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['passworld']
            email = uf.cleaned_data['email']
            #将表单写入数据库
            user = NormalUser()
            user.username = username
            user.password = password
            user.email = email
            user.save()
            #返回注册成功页面
            return render_to_response('submit_success.html',{'username':username})
    else:
        uf = UserForm()
    return render(request,'register.html',{'uf':uf})

